package com.cakeshop.servelt;

import com.cakeshop.model.Comment;
import com.cakeshop.service.CommentService;
import com.cakeshop.service.impl.CommentServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * 这里负责用户对评论的点赞/点踩行为的处理
 *
 * @author nineice
 */
@WebServlet(name = "UserCommentLikeServlet", value = "/user_like")
public class UserCommentLikeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        CommentService commentService = new CommentServiceImpl();
        Comment comment = commentService.getCommentById(Integer.parseInt(request.getParameter("id")));
        TreeSet<Integer> likeSet = (TreeSet<Integer>) request.getSession().getAttribute("likeSet");
        TreeSet<Integer> noLikeSet = (TreeSet<Integer>) request.getSession().getAttribute("noLikeSet");

        if ("yes".equals(request.getParameter("like"))) {
            // 为评论点赞
            if (noLikeSet.contains(comment.getId())) {
                noLikeSet.remove(comment.getId());
                commentService.noLikes(comment, -1);
            }
            if (!likeSet.contains(comment.getId())) {
                likeSet.add(comment.getId());
                commentService.likes(comment, 1);
            } else {
                likeSet.remove(comment.getId());
                commentService.likes(comment, -1);
            }
        } else if ("no".equals(request.getParameter("like"))) {
            // 为评论点踩
            if (likeSet.contains(comment.getId())) {
                likeSet.remove(comment.getId());
                commentService.likes(comment, -1);
            }
            if (!noLikeSet.contains(comment.getId())) {
                noLikeSet.add(comment.getId());
                commentService.noLikes(comment, 1);
            } else {
                noLikeSet.remove(comment.getId());
                commentService.noLikes(comment, -1);
            }
        } else {
            System.out.println("???");
        }

        request.getSession().setAttribute("likeSet", likeSet);
        request.getSession().setAttribute("noLikeSet", noLikeSet);
        // 从哪来回哪去
        response.sendRedirect(request.getHeader("Referer"));
    }
}
